﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Parichay.Domain; using Parichay.Domain.Models;
using Parichay.Data.Helper;

namespace Parichay.MVC.Controllers
{
    public class MessageController : AuthController
    {
        //
        // GET: /Message/
        Domain.Interface.Data.IMessageRepository _messageRepository;

        public MessageController(Domain.Interface.Data.IMessageRepository messageRepository)
        {
            _messageRepository = messageRepository;
        }

        public ActionResult Index()
        {
            MessageHomeModel model = new MessageHomeModel();
            model.myMessages = MyMessages();


            return View(model);
        }

        public ActionResult MsgDtl(int id)
        {
            MemberMessage model = Data.Helper.NHibernateHelper.UniqueResult<MemberMessage>(null, "Id", id);
            return View(model);
        }

        private IList<Parichay.Domain.MemberMessage> MyMessages()
        {
            var lst= _messageRepository.GetMessagesByUserId(LoggedInUserKey, 10, 0);
            return (lst);
        }

        public ActionResult Reply(int id, int rId, int rUrl)
        {
            return View();
        }

        [HttpPost]
        public ActionResult ReplyMessage(int id, int rId, int rUrl, MemberMessage model)
        {

                model.ParentId = new MemberMessage() { Id = id };
                model.Recipient = new MemberDetails() { Id = rId };
                model.rUrl = rUrl;

            return AddMessage(model);
        }
        [HttpPost]
        public ActionResult AddMessage(MemberMessage model)
        {
            var result = new JsonResponse();
            if (string.IsNullOrEmpty(model.Text))
            {
                result.isSuccessful = false;
                TempData["message"] = result.errorMessage = "Message cannot be blank.";
            }
            else
            {
                //update the database
                if (IsUserAuthenticated)
                {
                    try
                    {

                        MemberDetails thisUsr = _memberRepository.getUserById(LoggedInUserKey);

                        var msg = new MemberMessage
                        {
                            Text = model.Text.Replace("\r\n", " "),
                            Modifiedon = DateTime.Now.ToUniversalTime(),
                            Createdon = DateTime.Now.ToUniversalTime(),
                            Sender = thisUsr,
                            Type = ((int)model.Type),
                            IsPrivate = false,
                            Source = "parichay",
                            Recipient = thisUsr
                        };


                        if (model.ParentId != null)
                        {
                            msg.ParentId = _messageRepository.GetMessageById(model.ParentId.Id);
                        }
                        if (model.Recipient != null)
                        {
                            MemberDetails recUsr = _memberRepository.getUserById(model.Recipient.Id);
                            if (recUsr == null)
                            {
                                throw new Exception("This user do not have profile information. Message cannot be sent.");
                            }
                            else
                            {
                                msg.Recipient = recUsr;
                            }
                            
                        }

                        
                        NHibernateHelper.Save<MemberMessage>(msg);

                        //Sending Notify Now
                        try
                        {
                            if (msg.Sender.Id != msg.Recipient.Id)
                            {
                                string msgUrl = "<a href='" + Url.Action("MsgDtl", "Message", new { id = msg.Id }) + "' >reply</a>";
                                Alert(msg.Recipient.Id, string.Format("You have received a ({0}) to from: {1}", msgUrl, msg.Sender.Givennm));
                            }
                        }
                        catch (Exception ex1)
                        {

                            _logRepository.Log(new Exception("Error Sending Message Alert=>", ex1));
                        }

                        result.Id = msg.Id.ToString();

                        

                        result.isSuccessful = true;
                        TempData["message"] = result.responseText = "Message Sent Successfully";
                    }
                    catch (Exception excp1)
                    {
                        _logRepository.Log(new Exception("Error Sending Message=>", excp1));
                        result.isSuccessful = false;
                        TempData["message"] = result.errorMessage = "Failed to save message. Error: " + excp1.Message;
                    }
                }
                else
                {
                    result.isSuccessful = false;
                    TempData["message"] = result.errorMessage = "You must be logged in to post a message";
                }
            }
            if (IsJsonRequest())
            { return Json(result); }
            else
            {
                    return RedirectToAction("Index",((Parichay.AppConstants.ReturnContollerHomes)model.rUrl).ToString());
            }
        }
        [HttpPost]
        public ActionResult Delete(int id,int? rUrl)
        {
            var result = new JsonResponse();

            try
            {
                //delete message from database
                //make sure the user has the right to delete

                //get the message
                MemberMessage lstResults = Data.Helper.NHibernateHelper.UniqueResult<MemberMessage>(null, new string[] { "Id", "Sender.Id" }, new object[] { id, LoggedInUserKey });
                //MemberMessage lstResults = m_PersistenceManager.UniqueResult<MemberMessage>(null,  "Id",id );

                if (lstResults != null)
                {
                    MemberMessage message = lstResults;

                    int childCount = Data.Helper.NHibernateHelper.Count("select m.Id from MemberMessage m where m.ParentId.Id=?",id,NHibernate.NHibernateUtil.Int32,false);

                    if (childCount > 0)
                    {
                        result.isSuccessful = false;
                        TempData["message"] = result.errorMessage = "You cannot delete messages that have been replied to.";
                    }
                    else
                    {
                        if (message.Type == 2)
                        {
                            ////delete the files
                            //try
                            //{
                            //    AmazonHelper.Delete(message.ImageFilename); //image
                            //    AmazonHelper.Delete(message.ThumbnailFilename); //thumbnail
                            //}
                            //catch (Exception ex)
                            //{
                            //    Utils.Log(ex);
                            //}
                        }

                        Data.Helper.NHibernateHelper.Delete<MemberMessage>(message);
                        result.isSuccessful = true;
                        TempData["message"] = result.errorMessage = "Message deleted.";
                    }
                }
                else
                {
                    result.isSuccessful = false;
                    TempData["message"] = result.errorMessage = "Message already deleted or you don't have permission to delete it.";
                }
            }
            catch (Exception exc)
            {
                result.isSuccessful = false;
                _logRepository.Log(new Exception("Error deleting message. ==> ", exc));
                TempData["message"] = result.errorMessage = "Unexpected error while deleting message.";
            }
            if (IsJsonRequest())
            {
                return Json(result);
            }
            else
            {
                int rUrl2 = rUrl.HasValue ? rUrl.Value : 0;
                return RedirectToAction("Index",((Parichay.AppConstants.ReturnContollerHomes)rUrl2).ToString());
            }
        }

        public ActionResult Del(int id,int? rUrl)
        {
            return Delete(id,rUrl);
        }

        private IList<Parichay.Domain.MemberMessage> getMessagesByUId(int uId, int pageSize, int pageIndex)
        {
            var lst = _messageRepository.GetMessagesByUserId(uId, pageSize, pageIndex);
            //msgs.SortDescending(m => m.Createdon);
            return (lst);
        }

        [HttpPost]
        public ActionResult Index(MessageHomeModel model)
        {
            //string srchQuery = "from MemberDetails p where p.Givennm like ?";
            //System.Collections.IList rtrn = Data.Helper.NHibernateHelper.Find(srchQuery, "%"+givenEmail+"%", NHibernate.NHibernateUtil.String,false);

            switch (model.btnSubmit)
            {
                case ("Find"):
            IList<MemberDetails> rtrn = Data.Helper.NHibernateHelper.FetchProjection<MemberDetails>(new string[] { "Givennm", "Id", "PicId", "Institute", "Addr" }, "Givennm", "%" + model.txtUserNameToSearch + "%", 0, 10, true, null, false);
            model.userSearchResults = rtrn;
                    break;
                case("Send"):
                    if ((model.selectedUserIds==null)||(model.selectedUserIds.Length==0)) { ModelState.AddModelError("", "No User Was Selected. Please select a User's checkbox before sending text message."); break; }
                    if (string.IsNullOrEmpty(model.txtMessageToSend)) { ModelState.AddModelError("txtMessageToSend", "Empty Message Cannot be Sent."); break; }

                    try
                    {
                        foreach (string usrId in model.selectedUserIds)
                        {
                            MemberMessage msg = new MemberMessage();
                            msg.Text = model.txtMessageToSend;
                            msg.Sender = _memberRepository.getUserById(LoggedInUserKey);
                            msg.Recipient = _memberRepository.getUserById(int.Parse(usrId));
                            msg.Createdon = DateTime.Now;
                            msg.Source = "parichay";
                            msg.Type = 0;
                            msg.Modifiedon = DateTime.Now;
                            msg.IsPrivate = true;

                            NHibernateHelper.Save<MemberMessage>(msg);

                            //Sending Notify Now
                            try
                            {
                                if (msg.Sender.Id != msg.Recipient.Id)
                                {
                                    string msgUrl = "<a href='" + Url.Action("MsgDtl", "Message", new { id = msg.Id }) + "' >reply</a>";
                                    Alert(msg.Recipient.Id, string.Format("You have received a ({0}) to from: {1}", msgUrl, msg.Sender.Givennm));
                                }
                            }
                            catch (Exception ex1)
                            {

                                _logRepository.Log(new Exception("Error Sending Message Alert=>", ex1));
                            }

                        }

                        ModelState.AddModelError("txtMessageToSend", "Message was sent to following users" + string.Join(",",model.selectedUserIds));
                    }
                    catch (Exception exc)
                    {
                        _logRepository.Log("Error Sending Message:"+exc.Message+exc.StackTrace,LogType.Error);
                        ModelState.AddModelError("", "Error has occured while sending messge. Admins are notified. We're sorry for inconvenience.");
                    }

                    break;
                default:
                    break;
            }
            model.myMessages = MyMessages();
            model.LoggedInUserKey = LoggedInUserKey;
            return View(model);
        }
    }
}
